package com.tiantianyuegou.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SyncStatusObserver;
import android.graphics.drawable.BitmapDrawable;
import android.nfc.Tag;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.adapter.SelectListAdapter;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.BankModel;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 选择已有的银行卡
 */
public class SelectBankActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private ImageView img_title;
    private TextView text_title, text_menu;
    private ListView list_select;

    private ImageView img_my_bank;
    private TextView text_my_bank;

    private SelectListAdapter selectListAdapter;

    private String type, tmTbId;
    private String TAG = "SelectBankActivity";

    private List<BankModel> bankModelList;
    private Context mContext;

    private int tbId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_bank);
        init();
    }

    @Override
    public void findViewByIds() {

    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData() {

    }

    private void init() {
        mContext = this;
        text_title = (TextView) findViewById(R.id.text_title);
        img_title = (ImageView) findViewById(R.id.img_title);
        text_menu = (TextView) findViewById(R.id.text_menu);

        text_menu.setVisibility(View.VISIBLE);

        text_menu.setText(R.string.select_menu);
        img_title.setOnClickListener(this);
        text_menu.setOnClickListener(this);

        tmTbId = getIntent().getStringExtra("tbId");
        type = getIntent().getStringExtra("type");
        img_my_bank = (ImageView) findViewById(R.id.img_my_bank);
        text_my_bank = (TextView) findViewById(R.id.text_my_bank);
        list_select = (ListView) findViewById(R.id.list_select);

        text_my_bank.setText("您没有添加过银行卡~");
        img_my_bank.setImageResource(R.mipmap.bank);


    }

    @Override
    protected void onResume() {
        super.onResume();
        bankModelList = new ArrayList<>();
        loadBank();

        if ("1".equals(type)) {
            text_title.setText(R.string.select_title);
            selectListAdapter = new SelectListAdapter(this, bankModelList, type);
            list_select.setAdapter(selectListAdapter);
            list_select.setOnItemClickListener(this);
            Log.e("tag", "if.type==1");
        } else if ("2".equals(type)) {
            text_title.setText("我的银行卡");
            selectListAdapter = new SelectListAdapter(this, bankModelList, type);
            list_select.setAdapter(selectListAdapter);
//            list_select.setOnItemClickListener(this);

            Log.e("tag", "if.type==2");
        }

    }

    /**
     * 获取银行卡列表
     */
    private void loadBank() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("tmId", SPHelper.getTmId());
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.BANK_LIST, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String response = responseInfo.result;
                try {

                    JSONObject object = new JSONObject(response);
                    Log.e(TAG, "SelectBankActivity     " + response);
                    if (object.getString("code").equals("100")) {


                        String member = object.getString("member");


                        Log.e(TAG, "SelectBackActivity      " + TextUtils.isEmpty(member));
                        JSONArray memberArray = new JSONArray(member);

                        if (memberArray.length() != 0) {
                            img_my_bank.setVisibility(View.GONE);
                            text_my_bank.setVisibility(View.GONE);
                            list_select.setVisibility(View.VISIBLE);

                        } else {
                            img_my_bank.setVisibility(View.VISIBLE);
                            text_my_bank.setVisibility(View.VISIBLE);
                            list_select.setVisibility(View.GONE);
                        }
                        for (int i = 0; i < memberArray.length(); i++) {
                            JSONObject temp = memberArray.getJSONObject(i);
                            String tbId = temp.getString("tbId");
                            String tbNumber = temp.getString("tbNumber");//银行卡号
                            String tbName = temp.getString("tbName");//持卡人姓名
                            String bank = temp.getString("bank");//银行名称
                            String tbIdcard = temp.getString("tbIdcard");//身份证号
                            String tbPhone = temp.getString("tbPhone");//手机号
                            BankModel model = new BankModel(tbId, tbNumber, tbName, bank, tbIdcard, tbPhone);
                            if (tmTbId != null && !"".equals(tmTbId)) {
                                if (tmTbId.equals(tbId)) {
                                    model.setIsSelected(true);
                                }
                            }
                            bankModelList.add(model);
                        }
                        selectListAdapter = new SelectListAdapter(SelectBankActivity.this, bankModelList, type);
                        list_select.setAdapter(selectListAdapter);
                        selectListAdapter.setDeleteListener(new SelectListAdapter.iDeleteListener() {
                            @Override
                            public void deleteBank(int position) {
                                Log.e("TAG", "do delete in activity");
//                    bankModelList.remove(position);
//                    selectListAdapter.notifyDataSetChanged();
                                tbId = position;
                                showpopupwindow(position);
                            }
                        });
                        selectListAdapter.notifyDataSetChanged();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                showMsg("请求服务器失败");
            }
        });
    }

    private void loadDelBank(final int position) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("tmId", SPHelper.getTmId());
        params.addBodyParameter("tbId", bankModelList.get(tbId).getTbId());
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.DELET_BANK, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String response = responseInfo.result;
                Log.e(TAG, response);
                try {
                    JSONObject object = new JSONObject(response);
                    String code = object.getString("code");
                    if ("100".equals(code)) {
                        bankModelList.remove(position);
                        selectListAdapter.notifyDataSetChanged();
                    } else {
                        String msg = object.getString("message");
                        showMsg(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_title:
                finish();
                break;
            case R.id.text_menu:
                Intent text_menu = new Intent();
                text_menu.setClass(SelectBankActivity.this, AddBankActivity.class);
                startActivity(text_menu);
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        for (int j = 1; j < bankModelList.size(); j++) {
            bankModelList.get(j).setIsSelected(false);
        }
        bankModelList.get(i).setIsSelected(true);
//       selectListAdapter.getNum(i);
        selectListAdapter.notifyDataSetChanged();
        if (type.equals("1")) {
            Log.e("tag", "type==1");
            Intent intent = new Intent(mContext, CashingActivity.class);
            String tbId = bankModelList.get(i).getTbId();
            String mBankname = bankModelList.get(i).getBank();
            String num = bankModelList.get(i).getTbNumber();
            String mBanknumber = num.substring(num.length() - 4);//后四位
            intent.putExtra("mBankname", mBankname);
            intent.putExtra("mBanknumber", mBanknumber);
            intent.putExtra("tbId", tbId);
            setResult(10002, intent);
            finish();
        } else if (type.equals("2")) {
            Log.e("tag", "type==2");
            tbId = i;
            showpopupwindow(i);

        }

    }

    private PopupWindow popupWindow = null;

    @SuppressLint("InflateParams")
    private void showpopupwindow(final int position) {
        View view = getLayoutInflater().inflate(R.layout.popupwindow_reminder,
                null);

        TextView text_hint = (TextView) view.findViewById(R.id.text_hint);
        text_hint.setText("您确定删除这张银行卡吗？");

        TextView txt_cancel2 = (TextView) view.findViewById(R.id.txt_cancel2);
        txt_cancel2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadDelBank(position);
                popupWindow.dismiss();
            }
        });
        TextView txt_confirm = (TextView) view.findViewById(R.id.txt_confirm);
        txt_confirm.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                popupWindow.dismiss();

            }
        });

        popupWindow = new PopupWindow(view, ViewPager.LayoutParams.MATCH_PARENT,
                ViewPager.LayoutParams.MATCH_PARENT, true);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAtLocation(list_select, Gravity.CENTER, 0, 0);

    }
}
